package com.fesine.realm;

import com.fesine.dao.UserDao;
import com.fesine.entity.User;
import com.fesine.util.DbUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.sql.Connection;

/**
 * Created by Fesine on 2016/6/13.
 */
public class MyRealm extends AuthorizingRealm {

    private UserDao userDao = new UserDao();
    private DbUtil dbUtil = new DbUtil();

    Logger logger = Logger.getLogger(MyRealm.class);
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();//获取用户名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Connection con = null;
        try {
            con = dbUtil.getCon();
            //通过用户名获取角色
            authorizationInfo.setRoles(userDao.getRoles(con, userName));
            //通过用户名获取权限
            authorizationInfo.setStringPermissions(userDao.getPermissions(con, userName));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authorizationInfo;
    }

    /**
     * 验证当前登录的用户
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        String userName = (String) token.getPrincipal();//获取用户名
        Connection con = null;
        try {
            con = dbUtil.getCon();
            User user = userDao.getByUserName(con, userName);//根据用户名查询用户信息
            if (user != null) {
                //封装验证信息，用户名和密码，私钥，与提交的用户数据进行比对
                AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
                        user.getUserName(), user.getPassword(), "fesine");
                return authcInfo;
            } else {
                logger.info("用户名不存在！");
                return null;
            }
        } catch (Exception e) {
            logger.info("用户登录验证失败！");
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
